<template>
  <div class="real-time-material-price">
    <h3>实时物料价格</h3>
      <el-table :data="materialPrices.slice().reverse()" border style="width: 100%">
        <el-table-column prop="materialName" label="类型" width="50" align="center"></el-table-column>
        <el-table-column label="回购" align="center">
          <template slot-scope="scope">
          <span :class="getPriceClass(scope.row.lastUp)">
            {{ scope.row.price}}
          </span>
          </template>
        </el-table-column>
        <el-table-column label="销售" align="center">
          <template slot-scope="scope">
          <span :class="getPriceClass(scope.row.lastSellUp)">
            {{ scope.row.sellPrice }}
          </span>
          </template>
        </el-table-column>
      </el-table>
  </div>
</template>

<script>
import { getPrices } from '@/api/index'

export default {
  name: 'RealTimeMaterialPrice',
  data() {
    return {
      materialPrices: []
    }
  },
  mounted() {
    this.fetchMaterialPrices()
    // 监听 WebSocket 更新
    this.$onWebSocket('materialPriceUpdate', this.updateMaterialPrices);
  },
  methods: {
    async fetchMaterialPrices() {
      try {
        const prices = await getPrices()
        console.log(prices);
        this.materialPrices = prices;
      } catch (error) {
        console.error('获取物料价格失败:', error)
      }
    },
    updateMaterialPrices(data) {
      this.materialPrices = data.data;
    },
    // 获取价格样式类
    getPriceClass(up) {
      if (up == true) {
        return 'price-up';
      } else {
        return 'price-down';
      }
    },
  }
}
</script>

<style scoped>
.price-up {
  color: #f56c6c;
}
.price-down {
  color: #67c23a;
}
.real-time-material-price {
  padding: 16px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.real-time-material-price h3 {
  font-size: 18px;
  margin-bottom: 12px;
}

.real-time-material-price ul {
  list-style: none;
  padding: 0;
  margin: 0;
}

.real-time-material-price li {
  font-size: 14px;
  margin-bottom: 8px;
}
</style>